#!/usr/bin/perl
# 2014/04/14 BEDファイルをIGORで描画できるように変形する

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 2 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [bed file] -s (use different value for each strand)\n";
}

my %opt;
getopts("i:s", \%opt);
my $FILE_bed = $opt{i};


my %BED;
my $fh = IO::File->new($FILE_bed) or die "cannot open $FILE_bed: $!";
while($_ = $fh->getline()){
	s/\r?\n//;
	if(m/^#/){
		next;
	}

	my ($chr, $start, $end, $name, $t1, $direction, @others) = split /\t/;
	my $value = 1;
	if(exists $opt{s} and $direction eq '-'){
		$value = -1;
	}

	for(my $i = $start + 1; $i <= $end; $i+= 100){
		push @{$BED{$chr}}, [$i, $value];
	}
}

my $MAX1 = scalar @{$BED{"I"}};
my $MAX2 = scalar @{$BED{"II"}};
my $MAX3 = scalar @{$BED{"III"}};
my $MAX = $MAX1;
if($MAX2 > $MAX){
	$MAX = $MAX2;
}
if($MAX3 > $MAX){
	$MAX = $MAX3;
}

print "points\tpos_chr1\tval_chr1\tpos_chr2\tval_chr2\tpos_chr3\tval_chr3\n";
for(my $i = 0; $i < $MAX; $i++){
	print "$i";
	foreach my $chr(qw(I II III)){
		my ($pos, $val) = ("", "");
		if(@{$BED{$chr}} > 0){
			my $data = shift @{$BED{$chr}};
			($pos, $val) = @$data;
		}
		print "\t$pos\t$val";
	}
	print "\n";
}

